import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserInfo, logout as apiLogout } from '@/api/user'
import {
  getToken,
  setToken,
  clearAuth,
  isLoggedIn as checkLoggedIn,
  getUserInfo as getStoredUserInfo,
} from '@/utils/auth'
import router from '@/router'
import { ElMessage } from 'element-plus'

// 不再需要会话超时监听时间间隔，由request.js统一管理
// const TIMEOUT_CHECK_INTERVAL = 60 * 1000 // 1分钟检查一次

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(getStoredUserInfo() || {})
  const roles = ref([])
  const permissions = ref([])

  // 计算属性
  const isLoggedIn = computed(() => checkLoggedIn())
  const hasRole = computed(() => (roleId) => {
    return roles.value.includes(roleId)
  })
  const nickname = computed(() => userInfo.value?.nickname || userInfo.value?.username || '未登录')
  const avatar = computed(() => userInfo.value?.avatar || '')

  // 设置Token
  function setUserToken(newToken) {
    token.value = newToken
    setToken(newToken)
  }

  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = info
    roles.value = info?.roles || []
    permissions.value = info?.permissions || []
  }

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const data = await getUserInfo()
      setUserInfo(data)
      return data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  // 登出
  async function logout() {
    try {
      await apiLogout()
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地存储中的认证信息
      clearAuth()

      // 重置状态
      resetState()

      // 检查当前路由是否为管理端路由
      const isAdminRoute = router.currentRoute.value.path.includes('/admin')

      // 根据当前路由决定跳转到哪个登录页
      if (isAdminRoute) {
        router.push('/admin/login')
      } else {
        router.push('/login')
      }

      ElMessage.success('已退出登录')
    }
  }

  // 重置状态
  function resetState() {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    permissions.value = []
  }

  // 清除用户信息
  function clearUserInfo() {
    // 清除本地存储中的认证信息
    clearAuth()

    // 重置状态
    resetState()

    // 检查当前路由是否为管理端路由
    const isAdminRoute = router.currentRoute.value.path.includes('/admin')

    // 根据当前路由决定跳转到哪个登录页
    if (isAdminRoute) {
      router.push('/admin/login')
    } else {
      router.push('/login')
    }
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    isLoggedIn,
    hasRole,
    nickname,
    avatar,
    setUserToken,
    setUserInfo,
    fetchUserInfo,
    logout,
    resetState,
    clearUserInfo,
  }
})
